<template>
  <input v-model="keyword" />
  <h1>{{ keyword }}</h1>
</template>

<script>
import { customRef } from "vue";

export default {
  name: "App",
  setup() {
    function myRef(value, delay) {
      return customRef((track, trigger) => {
        let timer;
        return {
          get() {
            track();
            return value;
          },
          set(newValue) {
            // 防止设置太多定时器，因此要每次清理定时器，然后只取最后一次以防抖
            clearTimeout(timer);
            timer = setTimeout(() => {
              value = newValue;
              trigger();
            }, delay);
          },
        };
      });
    }

    let keyword = myRef("hello", 500);

    return {
      keyword,
    };
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
